package com.gxa.pingan.service.impl;

import com.gxa.pingan.common.ExceptionCode;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.mapper.CouponMapper;
import com.gxa.pingan.pojo.Coupon;
import com.gxa.pingan.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponMapper couponMapper = null;
    @Override
    public void add(Coupon coupon) throws Exception {
        if (coupon == null) {
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        Long methodId = coupon.getMethodId();
        coupon.setInUse(true);
        coupon.setGetNum(0L);
        Integer add = couponMapper.add(coupon);
        if (add == 0) {
            throw new BusinessException(ExceptionCode.FAILED_OPERATION);
        }
    }

    @Override
    public List<Map<String, Object>> getMethod() {

        return couponMapper.getMethod();
    }

    @Override
    public List<Coupon> getList(Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        return couponMapper.selectAll(offset,size);
    }

    @Override
    public Integer getListCount() {
        return couponMapper.selectAll(null,null).size();
    }

    @Override
    public void update(Coupon coupon) throws BusinessException {
        if (coupon == null || coupon.getId() == null) {
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        if (couponMapper.selectById(coupon.getId()) == null) {
            throw new BusinessException(ExceptionCode.NO_SUCH_COUPON);
        }
        Integer update = couponMapper.update(coupon);
        if (update == 0) {
            throw new BusinessException(ExceptionCode.FAILED_OPERATION);
        }
    }

    @Override
    public void updateStatus(Long id, Boolean status) throws BusinessException {
        Coupon coupon = new Coupon();
        coupon.setId(id);
        coupon.setInUse(status);
        if (couponMapper.selectById(coupon.getId()) == null) {
            throw new BusinessException(ExceptionCode.NO_SUCH_COUPON);
        }
        Integer update = couponMapper.update(coupon);
        if (update == 0) {
            throw new BusinessException(ExceptionCode.FAILED_OPERATION);
        }
    }


}
